package com.bestcem.xm.txtanls.grpc.client;


import com.bestcem.bp.grpc.v1.base.Code;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.txtanls.grpc.dto.IdMapNodeDTO;
import com.bestcem.xm.txtanls.service.dto.user.OrgInfoDTO;
import com.bestcem.xm.user.grpc.v1.common.IdRelation;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class TxtanlsUserGrpcService {


    @GrpcClient(GrpcClientNames.DS_USER)
    private OrgServiceGrpc.OrgServiceBlockingStub orgServiceBlockingStub;


    @GrpcClient(GrpcClientNames.DS_USER)
    private UserServiceGrpc.UserServiceBlockingStub userServiceBlockingStub;

    /**
     * 根据orgCode或OrgId获取租户信息
     *
     * @param orgCode
     * @param orgId
     * @return
     */
    public OrgInfoDTO getOrgInfoByOrgCodeOrId(String orgCode, String orgId) {
        if (StringUtils.isAllBlank(orgCode, orgId)) {
            log.error("[Txtanls]:WARN: BPUser getOrgByIdOrCode parameter not found");
            return null;
        }
        GetOrgByIdOrCodeRequest.Builder builder = GetOrgByIdOrCodeRequest.newBuilder();
        if (StringUtils.isNotBlank(orgCode)) {
            builder.setCode(orgCode);
        }
        if (StringUtils.isNotBlank(orgId)) {
            builder.setId(orgId);
        }
        try {
            GetOrgByIdOrCodeResponse response = orgServiceBlockingStub.getOrgByIdOrCode(builder.build());
            if (Objects.isNull(response) || Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Txtanls] BPUser getOrgByIdOrCode,orgId:{},orgCode:{}, Error; ErrorMsg: {}", orgId, orgCode, response);
                return null;
            }

            return this.responseToOrganizationDTO(response);
        } catch (Exception e) {
            log.error("[Txtanls] BPUser getOrgByIdOrCode,orgId:{},orgCode:{}, Error; ErrorMsg: {}", orgId, orgCode, e.getMessage(), e);
            return null;
        }
    }

    /**
     * copy_sample 复制旧公司user
     *
     * @param srcId 旧公司ID
     * @param dstId 新公司ID
     * @return id对应关系
     * @author XiaoYunSong <ys.xiao@idiaoyan.com>
     * @date 2021/8/30 17:39
     * //todo 后续需要与工单的该方法合并为公共方法
     */
    @Nullable
    public List<IdMapNodeDTO> getUserMapBySrcIdAndDstId(String srcId, String dstId) {
        ListUserIdMapsRequest.Builder builder = ListUserIdMapsRequest.newBuilder();
        builder.setSrcOrgId(srcId);
        builder.setDstOrgId(dstId);
        try {
            ListUserIdMapsResponse response = userServiceBlockingStub.listUserIdMaps(builder.build());
            if (Objects.isNull(response) || Code.ERROR.equals(response.getStatus().getCode())) {
                log.error("[Ticket] USER getGroupLevelMapBySrcIdAndDstId {}-{} Error; ErrorMsg: {}"
                        , srcId, dstId, response);
                return null;
            }
            return infoToIdMapNodeDTOList(response.getIdRelationsList());
        } catch (Exception e) {
            log.error("[Ticket] USER getGroupLevelMapBySrcIdAndDstId {}-{} Error; ErrorMsg: {}"
                    , srcId, dstId, e.getMessage(), e);
            return null;
        }
    }


    private OrgInfoDTO responseToOrganizationDTO(GetOrgByIdOrCodeResponse response) {
        Organization organization = response.getOrg();
        OrgInfoDTO dto = new OrgInfoDTO();
        dto.setCheckSmtpId(organization.getAuditSmtpId());
        dto.setCode(organization.getCode());
        dto.setContent(organization.getContent());
        dto.setCorporateWallet(organization.getWalletId());
        dto.setEmail(organization.getAdminEmail());
        // 格式转换错误先注释，这些字段暂时没有使用
//        dto.setExpiryDt(organization.getExpiryDt());
        dto.setFooter(organization.getFooterValue());
//        dto.setFreeExpiryDt(organization.getFreeExpiryDt());
        dto.setHasNotifySales(organization.getNotifySales());
        dto.setId(organization.getId());
        dto.setIndustryID(organization.getIndustryId());
        dto.setComplete(organization.getComplete());
        dto.setDeliverCheck(organization.getDeliverAudit());
        dto.setIsInner(organization.getInner());
        dto.setMobile(organization.getAdminPhone());
        dto.setName(organization.getName());
        dto.setOrgAdmin(organization.getAdminName());
//        dto.setPaasConf(organization.getPaasConf());
        dto.setPackageID(organization.getPackageId());
        dto.setPrivateKeyId(organization.getPriId());
        dto.setPublicKey(organization.getPubFilePath());
        // 因为其报错，所以注释。代码中没用到这个字段
//        dto.setRootGroupList(organization.getRootGroupListList());
//        dto.setSkin(organization.getSkin());
        dto.setSmsPrice(organization.getSmsPrice());
        dto.setSource(organization.getSourceValue());
        dto.setStatus(organization.getStatusValue());
        return dto;
    }

    private static List<IdMapNodeDTO> infoToIdMapNodeDTOList(List<IdRelation> idMapNodes) {
        List<IdMapNodeDTO> idMapNodeDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(idMapNodes)) {
            for (IdRelation idMapNode : idMapNodes) {
                IdMapNodeDTO idMapNodeDTO = infoToIdMapNodeDTO(idMapNode);
                if (Objects.nonNull(idMapNodeDTO)) {
                    idMapNodeDTOList.add(idMapNodeDTO);
                }
            }
        }
        return idMapNodeDTOList;
    }

    private static IdMapNodeDTO infoToIdMapNodeDTO(IdRelation idMapNode) {
        if (Objects.isNull(idMapNode)) {
            return null;
        }
        IdMapNodeDTO idMapNodeDTO = new IdMapNodeDTO();
        idMapNodeDTO.setOldId(idMapNode.getOldId());
        idMapNodeDTO.setNewId(idMapNode.getNewId());
        return idMapNodeDTO;
    }
}
